// create_by linLinStyle on 2019/11/14 0014/下午 12:30
function Article() {

}

Article.prototype.listenUploadFileEvent = function () {
    var btn = $('#thumbnail-btn');
    btn.change(function () {
        var file = btn[0].files[0];
        var formDate = new FormData();
        formDate.append('file', file);
        myajax.post({
            'url': '/cms/upload_file/',
            'data': formDate,
            'processData': false,
            'contentType': false,
            'success': function (result) {
                if (result['code'] === 200) {
                    var url = result['data']['url'];
                    var thumbnailInput = $('#thumbnail-form');
                    thumbnailInput.val(url);
                }
            }
        });
    })
};

Article.prototype.initUEditor = function () {
    window.ue = UE.getEditor('ueditor', {
        'initialFrameHeight': 400,
        'serverUrl': '/ueditor/upload/'
    });
};

Article.prototype.listenSubmitEvent = function () {
    var btn = $('#submit-btn');
    var titleInput = $('input[name="title"]');
    var categoryInput = $('select[name="category"]');
    var descInput = $('input[name="desc"]');
    var thumbnailInput = $('input[name="thumbnail"]');
    btn.click(function (event) {
        event.preventDefault();
        var title = titleInput.val();
        var category = categoryInput.val();
        var desc = descInput.val();
        var thumbnail = thumbnailInput.val();
        var content = window.ue.getContent();
        if (!title) {
            linalert.alertInfo('请输入标题');
            return;
        } else if(!category) {
            linalert.alertInfo('请输入分类');
            return;
        } else if(!desc) {
            linalert.alertInfo('请输入描述');
            return;
        } else if (!thumbnail) {
            linalert.alertInfo('请输入缩略图地址');
            return;
        } else if (!content) {
            linalert.alertInfo('请输入文章内容');
            return;
        }
        myajax.post({
            'url': '/cms/add_article/',
            'data': {
                'title': title,
                'category': category,
                'desc': desc,
                'thumbnail': thumbnail,
                'content': content
            },
            'success': function (result) {
                if (result['code'] === 200) {
                    linalert.alertSuccess('文章发表成功', function () {
                        window.location.reload();
                    });
                }
            }
        });
    })
};

Article.prototype.run = function () {
    this.initUEditor();
    this.listenUploadFileEvent();
    this.listenSubmitEvent();
};

$(function () {
    var article = new Article();
    article.run();
});